﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CarbonExchange.WebControls;
using CarbonExchange.Bll;

public partial class UserControls_CarbonFootprintQuestion_Energy_Energy : CarbonExchange.WebControls.AuditQuestionBase
{
    private string InsulationChoiceName;
    private List<string> RenewableChoices = new List<string>();
    private string RenewableChoiceName;

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        rdoGreen.SelectedIndexChanged += new EventHandler(rdoGreen_SelectedIndexChanged);
        rdoElectricBills.SelectedIndexChanged += new EventHandler(rdoElectricBills_SelectedIndexChanged);
        rptTvs.ItemDataBinding += new EventHandler<CarbonExchange.WebControls.AmeeRepeater.ItemEventArgs>(rptTvs_ItemDataBinding);
        rptComputers.ItemDataBinding += new EventHandler<AmeeRepeater.ItemEventArgs>(rptComputers_ItemDataBinding);
        rptAppliances.ItemDataBinding += new EventHandler<AmeeRepeater.ItemEventArgs>(rptAppliances_ItemDataBinding);
        rptOthers.ItemDataBinding += new EventHandler<AmeeRepeater.ItemEventArgs>(rptOthers_ItemDataBinding);
        dsOvens.Select += new EventHandler<Acms.DataControls.EventDrivenDataSourceSelectEventArgs>(dsOvens_Select);
        rdoHeatingElectric.SelectedIndexChanged += new EventHandler(rdoHeatingElectric_SelectedIndexChanged);
        rdoHeatingBills.SelectedIndexChanged += new EventHandler(rdoHeatingBills_SelectedIndexChanged);
        ameeHeatingEstimate.LabelDataBound += new EventHandler<CarbonExchange.WebControls.AmeeDrillDown.LabelDataBindingEventArgs>(ameeHeatingEstimate_LabelDataBound);
        ameeHeatingEstimate.DropDownDataBinding += new EventHandler<CarbonExchange.WebControls.AmeeDrillDown.DropDownDataBindingEventArgs>(ameeHeatingEstimate_DropDownDataBinding);
        dsRenewable.Select += new EventHandler<Acms.DataControls.EventDrivenDataSourceSelectEventArgs>(dsRenewable_Select);
        rptRenewable.ItemDataBound += new EventHandler<Acms.WebControls.ItemDataBoundEventArgs>(rptRenewable_ItemDataBound);
        dsInsulation.Select += new EventHandler<Acms.DataControls.EventDrivenDataSourceSelectEventArgs>(dsInsulation_Select);
        cblInsulation.DataBound += new EventHandler(cblInsulation_DataBound);
        ameeHeatingType.LabelDataBound += new EventHandler<CarbonExchange.WebControls.AmeeDrillDown.LabelDataBindingEventArgs>(ameeHeatingType_LabelDataBound);
        ameeHeatingType.DropDownDataBinding += new EventHandler<CarbonExchange.WebControls.AmeeDrillDown.DropDownDataBindingEventArgs>(ameeHeatingType_DropDownDataBinding);
        ameeHeatingEstimate.ItemSelected += new EventHandler<AmeeDrillDown.ItemSelectedEventArgs>(ameeHeatingEstimate_ItemSelected);
        dsOneToTen.Select += new EventHandler<Acms.DataControls.EventDrivenDataSourceSelectEventArgs>(dsOneToTen_Select);
    }

    void dsOneToTen_Select(object sender, Acms.DataControls.EventDrivenDataSourceSelectEventArgs e)
    {
        var items = new int[]{1,2,3,4,5,6,7,8,9,10};
        e.SetData(items);
    }

    private void SetVisibleProperties()
    {
        //hide everything 
        pnlElectricBills.Visible = false;
        phElectricBills.Visible = false;
        phElectricEstimate.Visible = false;
        pnlHeatingElectric.Visible = false;
        pnlHeatingBills.Visible = false;
        phHeatingBills.Visible = false;
        phHeatingEstimate.Visible = false;
        //if not green traffif
        if (rdoGreen.SelectedValue == "0")
        {
            pnlElectricBills.Visible = true;
            if (rdoElectricBills.SelectedValue == "1")
            {
                phElectricBills.Visible = true;
            }
            else if (rdoElectricBills.SelectedValue == "0")
            {
                phElectricEstimate.Visible = true;
            }
            pnlHeatingElectric.Visible = true;
        }
        //if green tariff
        else if(rdoGreen.SelectedValue == "1")
        {
            pnlHeatingElectric.Visible = true;
        }

        //if showing heating questions check if electric
        if (pnlHeatingElectric.Visible)
        {
            //if not eletric ask about bills
            if (rdoHeatingElectric.SelectedValue == "0")
            {
                pnlHeatingBills.Visible = true;
                phHeatingBills.Visible = rdoHeatingBills.SelectedValue == "1";
                phHeatingEstimate.Visible = rdoHeatingBills.SelectedValue == "0";
            }
            //if eletric and not elric bills need to calculate eletric heating estimate
            else if (rdoHeatingElectric.SelectedValue == "1" && rdoElectricBills.SelectedValue == "0")
            {
                phHeatingEstimate.Visible = true;
            }
        }
    }

    void rdoGreen_SelectedIndexChanged(object sender, EventArgs e)
    {
        SetVisibleProperties();
    }

    void dsOvens_Select(object sender, Acms.DataControls.EventDrivenDataSourceSelectEventArgs e)
    {
        AmeeDataCatagoryFactory factory = new AmeeDataCatagoryFactory();
        var hobs = factory.GetByPath("home/appliances/cooking/hob", null);
        var ovens = factory.GetByPath("home/appliances/cooking/oven", null);

        var tmp = hobs.Choices.Select(x => new { Text = GetChoiceDisplayText(string.Concat(x, " Hob")), Value = string.Concat(hobs.Path, "?", hobs.ChoiceName, "=", x) });
        tmp = tmp.Union(ovens.Choices.Select(x => new { Text = GetChoiceDisplayText(string.Concat(x, " Oven")), Value = string.Concat(ovens.Path, "?", ovens.ChoiceName, "=", x) }));
        e.SetData(tmp);
    }

    void rptAppliances_ItemDataBinding(object sender, AmeeRepeater.ItemEventArgs e)
    {
        AmeeDrillDown ameeAppliance = e.Item.FindControl("ameeAppliance") as AmeeDrillDown;
        DropDownList ddlNumber = e.Item.FindControl("ddlNumber") as DropDownList;
        if (ameeAppliance != null && ddlNumber != null)
        {
            ameeAppliance.AddOptions(Answer.GetSetting<AmeeDrillDown.Option[]>(string.Format("ameeAppliance_{0}", e.Item.ItemIndex)));
            ddlNumber.Text = Answer.GetSetting<string>(string.Format("ddlNumber_{0}", e.Item.ItemIndex));
        }
    }

    void rptComputers_ItemDataBinding(object sender, AmeeRepeater.ItemEventArgs e)
    {
        AmeeDrillDown ameeComputer = e.Item.FindControl("ameeComputer") as AmeeDrillDown;
        DropDownList ddlNumber = e.Item.FindControl("ddlNumber") as DropDownList;
        DropDownList ddlComputerStandby = e.Item.FindControl("ddlComputerStandby") as DropDownList;
        if (ameeComputer != null && ddlNumber != null && ddlComputerStandby != null)
        {
            ameeComputer.AddOptions(Answer.GetSetting<AmeeDrillDown.Option[]>(string.Format("ameeComputer_{0}", e.Item.ItemIndex)));
            ddlNumber.Text = Answer.GetSetting<string>(string.Format("ddlNumber_{0}", e.Item.ItemIndex));
            ddlComputerStandby.Text = Answer.GetSetting<string>(string.Format("ddlComputerStandby_{0}", e.Item.ItemIndex));
        }
    }

    void rptOthers_ItemDataBinding(object sender, AmeeRepeater.ItemEventArgs e)
    {
        AmeeDrillDown ameeOther = e.Item.FindControl("ameeOther") as AmeeDrillDown;
        DropDownList ddlNumber = e.Item.FindControl("ddlNumber") as DropDownList;
        DropDownList ddlOtherStandby = e.Item.FindControl("ddlOtherStandby") as DropDownList;
        if (ameeOther != null && ddlNumber != null && ddlOtherStandby != null)
        {
            ameeOther.AddOptions(Answer.GetSetting<AmeeDrillDown.Option[]>(string.Format("ameeOther_{0}", e.Item.ItemIndex)));
            ddlNumber.Text = Answer.GetSetting<string>(string.Format("ddlNumber_{0}", e.Item.ItemIndex));
            ddlOtherStandby.Text = Answer.GetSetting<string>(string.Format("ddlOtherStandby_{0}", e.Item.ItemIndex));
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
    }

    private void rptTvs_ItemDataBinding(object sender, CarbonExchange.WebControls.AmeeRepeater.ItemEventArgs e)
    {
        var answerItemName = string.Concat("TV_", e.Item.ItemIndex);
        AmeeDrillDown ameeTV = e.Item.FindControl("ameeTV") as AmeeDrillDown;
        TextBox txtTvHours = e.Item.FindControl("txtTvHours") as TextBox;
        if (ameeTV != null && txtTvHours != null)
        {
            ameeTV.AddOptions(Answer.GetSetting<AmeeDrillDown.Option[]>(string.Concat(answerItemName, "_options")));
            txtTvHours.Text = Answer.GetSetting<string>(string.Concat(answerItemName, "_hours"));
        }
    }

    void rdoElectricBills_SelectedIndexChanged(object sender, EventArgs e)
    {
        SetVisibleProperties();
    }
    
    public override void DataBind()
    {
        if(!string.IsNullOrEmpty(Answer.GetSetting<string>("rdoGreen")))
            rdoGreen.Text = Answer.GetSetting<string>("rdoGreen");
        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("rdoElectricBills")))
            rdoElectricBills.Text = Answer.GetSetting<string>("rdoElectricBills");

        txtStandardLights.Text = Answer.GetSetting<string>("txtStandardLights");
        txtEcoLights.Text = Answer.GetSetting<string>("txtEcoLights");

        rptComputers.SetNumberOfItems(Answer.GetSetting<int>("rptComputers"));
        rptAppliances.SetNumberOfItems(Answer.GetSetting<int>("rptAppliances"));
        rptTvs.SetNumberOfItems(Answer.GetSetting<int>("rptTvs"));
        rptOthers.SetNumberOfItems(Answer.GetSetting<int>("rptOthers"));

        ddlElectricPeriod.SelectedValue = Answer.GetSetting<string>("ddlElectricPeriod");
        txtElectricValue.Text = Answer.GetSetting<string>("txtElectricValue");

        if (Audit != null && Audit.Country != null)
        {
            switch (Audit.Country.RegionInfo.TwoLetterISORegionName)
            {
                case "GB":
                case "IE":
                    ameeHeatingEstimate.Path = "home/heating";
                    break;
                case "US":
                    ameeHeatingEstimate.Path = "home/heating/us";
                    ameeHeatingEstimate.AddOption(new CarbonExchange.WebControls.AmeeDrillDown.Option() { Hidden = true, Choice = string.Format("State={0}", Audit.State), ChoiceText = Audit.State, Label = "State" });
                    break;
                case "CA":
                    ameeHeatingEstimate.Path = "home/heating/us";
                    ameeHeatingEstimate.AddOption(new CarbonExchange.WebControls.AmeeDrillDown.Option() { Hidden = true, Choice = "State=New York State", ChoiceText = "New York State", Label = "State" });
                    break;
                case "AU":
                    ameeHeatingEstimate.Path = "home/heating/us";
                    ameeHeatingEstimate.AddOption(new CarbonExchange.WebControls.AmeeDrillDown.Option() { Hidden = true, Choice = "State=Georgia", ChoiceText = "Georgia", Label = "State" });
                    break;
                case "CH":
                    ameeHeatingEstimate.Path = "home/heating/us";
                    ameeHeatingEstimate.AddOption(new CarbonExchange.WebControls.AmeeDrillDown.Option() { Hidden = true, Choice = "State=Colorado", ChoiceText = "Colorado", Label = "State" });
                    break;
                case "HK":
                    ameeHeatingEstimate.Path = "home/heating/us";
                    ameeHeatingEstimate.AddOption(new CarbonExchange.WebControls.AmeeDrillDown.Option() { Hidden = true, Choice = "State=Florida", ChoiceText = "Florida", Label = "State" });
                    break;
                case "JP":
                    ameeHeatingEstimate.Path = "home/heating/us";
                    ameeHeatingEstimate.AddOption(new CarbonExchange.WebControls.AmeeDrillDown.Option() { Hidden = true, Choice = "State=California", ChoiceText = "California", Label = "State" });
                    break;
                case "AE":
                    ameeHeatingEstimate.Path = "home/heating/us";
                    ameeHeatingEstimate.AddOption(new CarbonExchange.WebControls.AmeeDrillDown.Option() { Hidden = true, Choice = "State=Hawaii", ChoiceText = "Hawaii", Label = "State" });
                    break;
                default:
                    ameeHeatingEstimate.Path = "home/heating";
                    break;
            }
        }
        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("rdoHeatingElectric")))
            rdoHeatingElectric.Text = Answer.GetSetting<string>("rdoHeatingElectric");

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("rdoHeatingBills")))
            rdoHeatingBills.Text = Answer.GetSetting<string>("rdoHeatingBills");

        ameeHeatingType.AddOptions(Answer.GetSetting<CarbonExchange.WebControls.AmeeDrillDown.Option[]>("ameeHeatingType"));

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("ddlHeatingPeriod")))
            ddlHeatingPeriod.Text = Answer.GetSetting<string>("ddlHeatingPeriod");

        txtHeatingValue.Text = Answer.GetSetting<string>("txtHeatingValue");

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("ddlHeatingValueFormat")))
            ddlHeatingValueFormat.Text = Answer.GetSetting<string>("ddlHeatingValueFormat");

        //check the defaults havnt changed
        var tmpOptions = Answer.GetSetting<CarbonExchange.WebControls.AmeeDrillDown.Option[]>("ameeHeatingEstimate");
        var tmpPath = Answer.GetSetting<string>("ameeHeatingEstimatePath");
        if (tmpPath == ameeHeatingEstimate.Path && tmpOptions != null)
        {
            var existing = tmpOptions.Take(ameeHeatingEstimate.SelectedOptions.Count()).ToArray();
            var matching = true;
            for (var i = 0; i < existing.Count(); i++)
            {
                if (existing[i].Choice != ameeHeatingEstimate.SelectedOptions[i].Choice)
                {
                    matching = false;
                }
            }
            if (matching)
            {
                ameeHeatingEstimate.ClearOptions();
                ameeHeatingEstimate.AddOptions(tmpOptions);
            }
        }

        SetVisibleProperties();
        
        base.DataBind();
    }

    protected override bool SaveQuestion()
    {
        var completed = true;
        List<CarbonExchange.Bll.AnswerItem> itemsToKeep = new List<CarbonExchange.Bll.AnswerItem>();
        CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory = new CarbonExchange.Bll.AmeeProfileItemFactory();
        CarbonExchange.Bll.AmeeDataCatagoryFactory dataCategoryFactory = new CarbonExchange.Bll.AmeeDataCatagoryFactory();

        Answer.SetSetting<string>("rdoGreen", rdoGreen.SelectedValue);
        Answer.SetSetting<string>("rdoElectricBills", rdoElectricBills.SelectedValue);
        if (rdoGreen.SelectedValue == "0" && rdoElectricBills.SelectedValue == "1")
        {
            if (!SaveElectricityAmount(profileItemFactory, dataCategoryFactory, itemsToKeep))
            {
                completed = false;
            }
        }
        else if (rdoGreen.SelectedValue == "0" && rdoElectricBills.SelectedValue == "0")
        {
            if (!SaveElectricityEstimate(profileItemFactory, itemsToKeep))
            {
                completed = false;
            }
        }
        else if(rdoGreen.SelectedValue != "1")
        {
            completed = false;
        }

        Answer.SetSetting<string>("rdoHeatingElectric", rdoHeatingElectric.SelectedValue);
        if (rdoHeatingElectric.SelectedValue == "0")
        {
            Answer.SetSetting<string>("rdoHeatingBills", rdoHeatingBills.SelectedValue);
            if (rdoHeatingBills.SelectedValue == "1")
            {
                if (!SaveHeatingAmount(profileItemFactory, dataCategoryFactory, itemsToKeep))
                {
                    completed = false;
                }
            }
            else if (rdoHeatingBills.SelectedValue == "0")
            {
                if (!SaveHeatingEstimate(profileItemFactory, dataCategoryFactory, itemsToKeep))
                {
                    completed = false;
                }
            }
            else
            {
                completed = false;
            }
        }
        else if (rdoHeatingElectric.SelectedValue == "1" && rdoElectricBills.SelectedValue == "0" && rdoGreen.SelectedValue == "0")
        {
            if (!SaveHeatingEstimate(profileItemFactory, dataCategoryFactory, itemsToKeep))
            {
                completed = false;
            }
        }
        else if(rdoHeatingElectric.SelectedValue != "1")
        {
            completed = false;
        }


        var deleteItems = Answer.AnswerItems.Where(x => !itemsToKeep.Contains(x)).ToList();

        if (deleteItems.Count > 0)
        {
            //delete from Amee
            foreach (var item in deleteItems.Where(x => !string.IsNullOrEmpty(x.AmeeId)))
            {
                profileItemFactory.Delete(Audit.AuditKey, item.Path, item.AmeeId);
            }

            CarbonExchange.Bll.AnswerItemFactory answerItemFactory = new CarbonExchange.Bll.AnswerItemFactory();
            answerItemFactory.Delete(deleteItems);
            foreach (var del in deleteItems)
            {
                if (Answer.AnswerItems.Contains(del))
                    Answer.AnswerItems.Remove(del);
            }
        }
        return completed;
    }

    private bool SaveElectricityAmount(CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, CarbonExchange.Bll.AmeeDataCatagoryFactory dataCategoryFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        Answer.SetSetting<string>("ddlElectricPeriod", ddlElectricPeriod.SelectedValue);
        Answer.SetSetting<string>("txtElectricValue", txtElectricValue.Text);

        string itemName = "ElecticityBills";
        string path = "/home/energy/electricity";
        string choice = "country={0}";
        switch(Audit.Country.RegionInfo.TwoLetterISORegionName)
        {
            case "GB":
                choice = string.Format(choice, "United Kingdom");
                break;
            case "US":
                choice = string.Format(choice, "United States");
                break;
            case "CA":
                choice = string.Format(choice, "Canada");
                break;
            case "AU":
                choice = string.Format(choice, "Australia");
                break;
            case "CH":
                choice = string.Format(choice, "Switzerland");
                break;
            case "IE":
                choice = string.Format(choice, "Ireland");
                break;
            case "HK":
                choice = string.Format(choice, "China (Including Hong Kong)");
                break;
            case "JP":
                choice = string.Format(choice, "Japan");
                break;
            case "AE":
                choice = string.Format(choice, "United Arab Emirates");
                break;
            default:
                choice = string.Format(choice, Audit.Country.RegionInfo.EnglishName);
                break;
        }
        CarbonExchange.Bll.AmeeProfileItem tmpProfileItem = EnsureProfileItem(itemName, profileItemFactory, dataCategoryFactory, path, choice);

        var save = string.IsNullOrEmpty(tmpProfileItem.Id);
        
        int months = 0;
        try
        {
            months = int.Parse(ddlElectricPeriod.SelectedValue);
        }
        catch (FormatException)
        {
        }
        
        int amount = 0;
        try
        {
            amount = int.Parse(txtElectricValue.Text);
        }
        catch (FormatException)
        {
        }

        decimal result = 0m;
        if(months > 0m)
            result = (decimal)amount / (decimal)months;

        if (tmpProfileItem.GetValue<decimal>("kWhPerMonth") != result)
        {
            tmpProfileItem.SetValue<decimal>("kWhPerMonth", result);
            save = true;
        }
        if (save)
        {
            profileItemFactory.Save(tmpProfileItem);
        }


        itemsToKeep.Add(Answer.SetItem(itemName, tmpProfileItem, 1));

        return result > 0;
    }

    private bool SaveElectricityEstimate(CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        var complete = true;
        if (!SaveLights(profileItemFactory, itemsToKeep, false))
        {
            complete = false;
        }
        if (!SaveLights(profileItemFactory, itemsToKeep, true))
        {
            complete = false;
        }
        Answer.SetSetting("rptComputers", rptComputers.Items.Count());
        foreach (var item in rptComputers.Items)
        {
            if (!SaveComputerItem(item, profileItemFactory, itemsToKeep))
            {
                complete = false;
            }
        }
        Answer.SetSetting("rptAppliances", rptAppliances.Items.Count());
        foreach (var item in rptAppliances.Items)
        {
            if (!SaveAppliancesItem(item, profileItemFactory, itemsToKeep))
            {
                complete = false;
            }
        }
        Answer.SetSetting("rptTvs", rptTvs.Items.Count());
        foreach (var item in rptTvs.Items)
        {
            if (!SaveTvItem(item, profileItemFactory, itemsToKeep))
            {
                complete = false;
            }
        }
        Answer.SetSetting("rptOthers", rptOthers.Items.Count());
        foreach (var item in rptOthers.Items)
        {
            if (!SaveOtherItem(item, profileItemFactory, itemsToKeep))
            {
                complete = false;
            }
        }
        return complete;
    }

    private bool SaveAppliancesItem(AmeeRepeaterItem item, CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        var itemCompleted = true;
        var answerItemName = string.Concat("Appliance_", item.ItemIndex);
        AmeeDrillDown ameeAppliance = item.FindControl("ameeAppliance") as AmeeDrillDown;
        DropDownList ddlNumber = item.FindControl("ddlNumber") as DropDownList;
        if (ameeAppliance != null && ddlNumber != null)
        {
            Answer.SetSetting(string.Format("ameeAppliance_{0}", item.ItemIndex), ameeAppliance.SelectedOptions);
            Answer.SetSetting(string.Format("ddlNumber_{0}", item.ItemIndex), ddlNumber.Text);
            if (ameeAppliance.CurrentCategory.DataItemSelected)
            {
                int number = 1;
                try
                {
                    number = int.Parse(ddlNumber.Text);
                }
                catch(FormatException)
                {
                }
                var tmpProfileItem = EnsureProfileItem(answerItemName, profileItemFactory, ameeAppliance.CurrentCategory);

                var save = string.IsNullOrEmpty(tmpProfileItem.Id);
                if(save)
                {
                    profileItemFactory.Save(tmpProfileItem);
                }
                itemsToKeep.Add(Answer.SetItem(answerItemName, tmpProfileItem, number));
            }
            else
            {
                itemsToKeep.Add(Answer.SetItem(answerItemName, ameeAppliance.CurrentCategory));
                itemCompleted = false;
            }
        }

        return itemCompleted;
    }

    private bool SaveComputerItem(AmeeRepeaterItem item, CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        var itemCompleted = true;
        var answerItemName = string.Concat("Computer_", item.ItemIndex);
        AmeeDrillDown ameeComputer = item.FindControl("ameeComputer") as AmeeDrillDown;
        DropDownList ddlNumber = item.FindControl("ddlNumber") as DropDownList;
        DropDownList ddlComputerStandby = item.FindControl("ddlComputerStandby") as DropDownList;
        if (ameeComputer != null && ddlNumber != null && ddlComputerStandby != null)
        {
            Answer.SetSetting<AmeeDrillDown.Option[]>(string.Format("ameeComputer_{0}", item.ItemIndex), ameeComputer.SelectedOptions);
            Answer.SetSetting<string>(string.Format("ddlNumber_{0}", item.ItemIndex), ddlNumber.SelectedValue);
            Answer.SetSetting<string>(string.Format("ddlComputerStandby_{0}", item.ItemIndex), ddlComputerStandby.SelectedValue);

            if (ameeComputer.CurrentCategory.DataItemSelected)
            {
                var tmpProfileItem = base.EnsureProfileItem(answerItemName, profileItemFactory, ameeComputer.CurrentCategory);

                int number = 1;
                try
                {
                    number = int.Parse(ddlNumber.Text);
                }
                catch (FormatException)
                {
                }

                var save = string.IsNullOrEmpty(tmpProfileItem.Id);

                if (tmpProfileItem.GetValue<string>("onStandby") != ddlComputerStandby.SelectedValue)
                {
                    tmpProfileItem.SetValue<string>("onStandby", ddlComputerStandby.SelectedValue);
                    save = true;
                }

                if (tmpProfileItem.GetValue<int>("numberOwned") != number)
                {
                    tmpProfileItem.SetValue<int>("numberOwned", number);
                    save = true;
                }

                if (save)
                {
                    profileItemFactory.Save(tmpProfileItem);
                }

                itemsToKeep.Add(Answer.SetItem(answerItemName, tmpProfileItem, number));
            }
            else
            {
                itemCompleted = false;
                itemsToKeep.Add(Answer.SetItem(answerItemName, ameeComputer.CurrentCategory));
            }
        }
        else
        {
            itemCompleted = false;
        }
        return itemCompleted;
    }

    private bool SaveLights(CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep, bool lowEnergy)
    {
        string path = "/home/lighting/";
        string itemName = null;
        string choices = null;
        string propertyName = null;
        int value = -1;

        if (lowEnergy)
        {
            itemName = "EcoLightBulbs";
            choices = "type=lel";
            propertyName = "noOfLowEnergyLightBulbs";
            Answer.SetSetting<string>("txtEcoLights", txtEcoLights.Text);
            try
            {
                value = int.Parse(txtEcoLights.Text);
            }
            catch (FormatException)
            {
            }
        }
        else
        {
            itemName = "StandardLightBulbs";
            choices = "type=normal";
            propertyName = "noOfLightBulbs";
            Answer.SetSetting<string>("txtStandardLights", txtStandardLights.Text);
            try
            {
                value = int.Parse(txtStandardLights.Text);
            }
            catch (FormatException)
            {
            }
        }

        CarbonExchange.Bll.AnswerItem tmpAnswerItem = Answer.GetItemByName(itemName);
        CarbonExchange.Bll.AmeeProfileItem tmpProfileItem = null;
        if (tmpAnswerItem == null || string.IsNullOrEmpty(tmpAnswerItem.AmeeId))
        {
            CarbonExchange.Bll.AmeeDataCatagoryFactory dataFactory = new CarbonExchange.Bll.AmeeDataCatagoryFactory();
            var tmpDataItem = dataFactory.GetByPath(path, choices);
            if (tmpDataItem == null || !tmpDataItem.DataItemSelected)
            {
                throw new ApplicationException(string.Format("Could not find data item at at {0}?{1}", path, choices));
            }
            else
            {
                tmpProfileItem = profileItemFactory.CreateItem(tmpDataItem, Audit.AuditKey, DateTime.Now.ToString("f"), Audit.StartDate);
            }
        }
        else
        {
            tmpAnswerItem.Name = itemName;
            tmpProfileItem = profileItemFactory.GetByPath(Audit.AuditKey, path, tmpAnswerItem.AmeeId);
        }

        if (tmpProfileItem.GetValue<int>(propertyName) != value)
        {
            tmpProfileItem.SetValue<int>(propertyName, value);
            profileItemFactory.Save(tmpProfileItem);
        }

        tmpAnswerItem = Answer.SetItem(itemName, tmpProfileItem);

        itemsToKeep.Add(tmpAnswerItem);

        return value >= 0;

    }

    private bool SaveTvItem(AmeeRepeaterItem item, CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        var itemCompleted = true;
        var answerItemName = string.Concat("TV_", item.ItemIndex);
        AmeeDrillDown ameeTV = item.FindControl("ameeTV") as AmeeDrillDown;
        TextBox txtTvHours = item.FindControl("txtTvHours") as TextBox;
        if (ameeTV != null && txtTvHours != null)
        {
            Answer.SetSetting<AmeeDrillDown.Option[]>(string.Concat(answerItemName, "_options"), ameeTV.SelectedOptions);
            Answer.SetSetting<string>(string.Concat(answerItemName, "_hours"), txtTvHours.Text);
            if (ameeTV.CurrentCategory.DataItemSelected)
            {
                var tmpProfileItem = base.EnsureProfileItem(answerItemName, profileItemFactory, ameeTV.CurrentCategory);

                decimal hours = 0m;
                try
                {
                    hours = int.Parse(txtTvHours.Text);
                }
                catch (FormatException)
                {
                }

                if (tmpProfileItem.GetValue<decimal>("hoursPerMonth") != hours)
                {
                    tmpProfileItem.SetValue<decimal>("hoursPerMonth", hours);
                    profileItemFactory.Save(tmpProfileItem);
                }

                itemsToKeep.Add(Answer.SetItem(answerItemName, tmpProfileItem));
            }
            else
            {
                itemCompleted = false;
                itemsToKeep.Add(Answer.SetItem(answerItemName, ameeTV.CurrentCategory));
            }
        }
        else
        {
            itemCompleted = false;
        }
        return itemCompleted;
    }

    private bool SaveOtherItem(AmeeRepeaterItem item, CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        var itemCompleted = true;
        var answerItemName = string.Concat("Other_", item.ItemIndex);
        AmeeDrillDown ameeOther = item.FindControl("ameeOther") as AmeeDrillDown;
        DropDownList ddlNumber = item.FindControl("ddlNumber") as DropDownList;
        DropDownList ddlOtherStandby = item.FindControl("ddlOtherStandby") as DropDownList;
        if (ameeOther != null && ddlNumber != null && ddlOtherStandby != null)
        {
            Answer.SetSetting<AmeeDrillDown.Option[]>(string.Format("ameeOther_{0}", item.ItemIndex), ameeOther.SelectedOptions);
            Answer.SetSetting<string>(string.Format("ddlNumber_{0}", item.ItemIndex), ddlNumber.Text);
            Answer.SetSetting<string>(string.Format("ddlOtherStandby_{0}", item.ItemIndex), ddlOtherStandby.SelectedValue);

            if (ameeOther.CurrentCategory.DataItemSelected)
            {
                var tmpProfileItem = base.EnsureProfileItem(answerItemName, profileItemFactory, ameeOther.CurrentCategory);

                int number = 1;
                try
                {
                    number = int.Parse(ddlNumber.Text);
                }
                catch (FormatException)
                {
                }

                var save = string.IsNullOrEmpty(tmpProfileItem.Id);

                if (tmpProfileItem.GetValue<string>("onStandby") != ddlOtherStandby.SelectedValue)
                {
                    tmpProfileItem.SetValue<string>("onStandby", ddlOtherStandby.SelectedValue);
                    save = true;
                }

                if (tmpProfileItem.GetValue<int>("numberOwned") != number)
                {
                    tmpProfileItem.SetValue<int>("numberOwned", number);
                    save = true;
                }

                if (save)
                {
                    profileItemFactory.Save(tmpProfileItem);
                }

                itemsToKeep.Add(Answer.SetItem(answerItemName, tmpProfileItem, number));
            }
            else
            {
                itemCompleted = false;
                itemsToKeep.Add(Answer.SetItem(answerItemName, ameeOther.CurrentCategory));
            }
        }
        else
        {
            itemCompleted = false;
        }
        return itemCompleted;
    }

    void rdoHeatingElectric_SelectedIndexChanged(object sender, EventArgs e)
    {
        SetVisibleProperties();
    }

    void rdoHeatingBills_SelectedIndexChanged(object sender, EventArgs e)
    {
        SetVisibleProperties();
    }

    void ameeHeatingEstimate_LabelDataBound(object sender, CarbonExchange.WebControls.AmeeDrillDown.LabelDataBindingEventArgs e)
    {
        if (e.DataCatagory.ChoiceName == "homeDwellingType" || (e.DataCatagory.ChoiceName == "type" && e.DataCatagory.Path == "home/heating/us"))
        {
            //For "homeDwellingType" or "type" when address is american
            e.Label.Text = GetText("Home Type");
        }
        else if (e.DataCatagory.ChoiceName == "homeNoOfBedrooms" || e.DataCatagory.ChoiceName == "numberOfBedrooms")
        {
            e.Label.Text = GetText("No Bedrooms");
        }
        else if (e.DataCatagory.ChoiceName == "homeFuel" || e.DataCatagory.ChoiceName == "fuel")
        {
            e.Label.Text = GetText("Primary Heating Source");
        }
        else if (e.DataCatagory.ChoiceName == "homeAge")
        {
            e.Label.Text = GetText("Home Age");
        }
        else if (e.DataCatagory.ChoiceName == "type")
        {
            e.Label.Text = GetText("Heater Type");
        }
        else if (e.DataCatagory.ChoiceName == "state")
        {
            e.Label.Text = "State";
        }
    }

    void ameeHeatingEstimate_ItemSelected(object sender, AmeeDrillDown.ItemSelectedEventArgs e)
    {
        //if electricity is an option and already said that uses elec as primary heating source then preset it
        if (e.DataCatagory.Choices.Contains("electricity") && rdoElectricBills.SelectedValue == "0" && rdoHeatingElectric.SelectedValue == "1")
        {
            AmeeDrillDown.Option choice = new AmeeDrillDown.Option();
            choice.Choice = string.Format("{0}=electricity", e.DataCatagory.ChoiceName);
            choice.ChoiceText = "Electricity";
            choice.Hidden = true;
            choice.Label = "Fuel";
            ameeHeatingEstimate.AddOption(choice);
        }
        else if (e.DataCatagory.Choices.Contains("electricity"))
        {
            e.DataCatagory.Choices.Remove("electricity");
        }
    }

    void ameeHeatingEstimate_DropDownDataBinding(object sender, CarbonExchange.WebControls.AmeeDrillDown.DropDownDataBindingEventArgs e)
    {
        if (e.DataCatagory.ChoiceName == "homeFuel" || e.DataCatagory.ChoiceName == "fuel")
        {
            e.DataCatagory.Choices.Remove("electricity");
        }
    }

    void dsRenewable_Select(object sender, Acms.DataControls.EventDrivenDataSourceSelectEventArgs e)
    {
        CarbonExchange.Bll.AmeeDataCatagoryFactory factory = new CarbonExchange.Bll.AmeeDataCatagoryFactory();
        var item = factory.GetByPath("home/energy/renewable", null);
        var choices = item.Choices;
        RenewableChoices = new List<string>(choices);
        RenewableChoiceName = item.ChoiceName;
        e.SetData(choices);
    }

    void rptRenewable_ItemDataBound(object sender, Acms.WebControls.ItemDataBoundEventArgs e)
    {
        var choice = e.DataItem as string;
        var valRenewableItemReq = e.Item.FindControl("valRenewableItemReq") as RequiredFieldValidator;
        var valRenewableItemAmount = e.Item.FindControl("valRenewableItemAmount") as RangeValidator;
        var cboRenewableItem = e.Item.FindControl("cboRenewableItem") as CheckBox;
        var lblRenewableItemAmount = e.Item.FindControl("lblRenewableItemAmount") as Label;
        var txtRenewableItem = e.Item.FindControl("txtRenewableItem") as TextBox;
        var lblRenewableItemKey = e.Item.FindControl("lblRenewableItemKey") as Label;
        if (valRenewableItemAmount != null && cboRenewableItem != null && lblRenewableItemAmount != null && txtRenewableItem != null && lblRenewableItemKey != null)
        {
            cboRenewableItem.Checked = Answer.GetSetting<bool>(string.Concat("cboRenewableItem_", choice));
            cboRenewableItem.Text = GetChoiceDisplayText(choice);
            txtRenewableItem.Text = Answer.GetSetting<string>(string.Concat("txtRenewableItem_", choice));
            valRenewableItemReq.Visible = valRenewableItemReq.Enabled = valRenewableItemAmount.Visible = valRenewableItemAmount.Enabled = lblRenewableItemKey.Visible = txtRenewableItem.Visible = lblRenewableItemAmount.Visible = cboRenewableItem.Checked;
        }
    }

    protected void cboRenewableItem_CheckedChanged(object sender, EventArgs e)
    {
        var cboRenewableItem = sender as CheckBox;
        var valRenewableItemReq = cboRenewableItem.NamingContainer.FindControl("valRenewableItemReq") as RequiredFieldValidator;
        var valRenewableItemAmount = cboRenewableItem.NamingContainer.FindControl("valRenewableItemAmount") as RangeValidator;
        var lblRenewableItemAmount = cboRenewableItem.NamingContainer.FindControl("lblRenewableItemAmount") as Label;
        var txtRenewableItem = cboRenewableItem.NamingContainer.FindControl("txtRenewableItem") as TextBox;
        var lblRenewableItemKey = cboRenewableItem.NamingContainer.FindControl("lblRenewableItemKey") as Label;
        if (valRenewableItemAmount != null && cboRenewableItem != null && lblRenewableItemAmount != null && txtRenewableItem != null && lblRenewableItemKey != null)
        {
            valRenewableItemReq.Visible = valRenewableItemReq.Enabled = valRenewableItemAmount.Visible = valRenewableItemAmount.Enabled = lblRenewableItemKey.Visible = txtRenewableItem.Visible = lblRenewableItemAmount.Visible = cboRenewableItem.Checked;
        }
    }

    void dsInsulation_Select(object sender, Acms.DataControls.EventDrivenDataSourceSelectEventArgs e)
    {
        CarbonExchange.Bll.AmeeDataCatagoryFactory factory = new CarbonExchange.Bll.AmeeDataCatagoryFactory();
        var item = factory.GetByPath("/home/energy/insulation", null);
        var choices = item.Choices.Select(x => new { Text = GetChoiceDisplayText(x), Value = x });
        InsulationChoiceName = item.ChoiceName;
        e.SetData(choices);
    }

    void cblInsulation_DataBound(object sender, EventArgs e)
    {
        foreach (ListItem item in cblInsulation.Items)
        {
            string settingName = string.Concat("cblInsulation_", item.Value);
            item.Selected = Answer.GetSetting<bool>(settingName);
        }
    }

    void ameeHeatingType_LabelDataBound(object sender, CarbonExchange.WebControls.AmeeDrillDown.LabelDataBindingEventArgs e)
    {
        if (e.DataCatagory.ChoiceName == "type")
        {
            e.Label.Text = GetText("Primary Heating Source");
        }
    }

    void ameeHeatingType_DropDownDataBinding(object sender, CarbonExchange.WebControls.AmeeDrillDown.DropDownDataBindingEventArgs e)
    {
        if (e.DataCatagory.ChoiceName == "type")
        {
            e.DataCatagory.Choices.Remove("electricity");
        }
    }

    private bool SaveHeatingAmount(CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, CarbonExchange.Bll.AmeeDataCatagoryFactory dataCategoryFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        bool completed = true;

        Answer.SetSetting("ameeHeatingType", ameeHeatingType.SelectedOptions);
        Answer.SetSetting<string>("ddlHeatingPeriod", ddlHeatingPeriod.SelectedValue);
        Answer.SetSetting<string>("txtHeatingValue", txtHeatingValue.Text);
        Answer.SetSetting<string>("ddlHeatingValueFormat", ddlHeatingValueFormat.SelectedValue);

        string itemName = "HeatingBills";
        if (ameeHeatingType.CurrentCategory.DataItemSelected)
        {
            CarbonExchange.Bll.AmeeProfileItem tmpProfileItem = EnsureProfileItem(itemName, profileItemFactory, ameeHeatingType.CurrentCategory);
            int months = 0;
            try
            {
                months = int.Parse(ddlHeatingPeriod.SelectedValue);
            }
            catch (FormatException)
            {
            }

            int amount = 0;
            try
            {
                amount = int.Parse(txtHeatingValue.Text);
            }
            catch (FormatException)
            {
            }

            decimal result = 0;
            if (months > 0)
            {
                result = (decimal)amount / (decimal)months;
            }

            bool save = false;
            foreach (ListItem option in ddlHeatingValueFormat.Items)
            {
                if (option.Selected)
                {
                    if (tmpProfileItem.GetValue<decimal>(option.Value) != result)
                    {
                        save = true;
                        tmpProfileItem.SetValue<decimal>(option.Value, result);
                    }
                }
                else
                {
                    if (tmpProfileItem.GetValue<decimal>(option.Value) != 0m)
                    {
                        save = true;
                        tmpProfileItem.SetValue<decimal>(option.Value, 0m);
                    }
                }
            }

            if (save)
            {
                profileItemFactory.Save(tmpProfileItem);
            }

            var tmpAnswerItem = Answer.SetItem(itemName, tmpProfileItem);
            itemsToKeep.Add(tmpAnswerItem);
            if (!(result > 0))
            {
                completed = false;
            }
        }
        else
        {
            Answer.SetItem(itemName, ameeHeatingType.CurrentCategory);
            completed = false;
        }

        return completed;
    }

    private bool SaveHeatingEstimate(CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, CarbonExchange.Bll.AmeeDataCatagoryFactory dataCategoryFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        bool completed = true;
        //Save heating Estimate
        Answer.SetSetting<CarbonExchange.WebControls.AmeeDrillDown.Option[]>("ameeHeatingEstimate", ameeHeatingEstimate.SelectedOptions);
        Answer.SetSetting<string>("ameeHeatingEstimatePath", ameeHeatingEstimate.Path);
        string itemName = "HeatingEstimate";

        if (ameeHeatingEstimate.CurrentCategory.DataItemSelected)
        {
            CarbonExchange.Bll.AmeeProfileItem tmpProfileItem = EnsureProfileItem(itemName, profileItemFactory, ameeHeatingEstimate.CurrentCategory);
            if (string.IsNullOrEmpty(tmpProfileItem.Id))
            {
                profileItemFactory.Save(tmpProfileItem);
            }
            itemsToKeep.Add(Answer.SetItem(itemName, tmpProfileItem));
        }
        else
        {
            completed = false;
            itemsToKeep.Add(Answer.SetItem(itemName, ameeHeatingEstimate.CurrentCategory));
        }

        //save each renewable checked
        int i = 0;
        foreach (var item in rptRenewable.Items)
        {
            string choice = RenewableChoices[i];
            CheckBox cboRenewableItem = item.FindControl("cboRenewableItem") as CheckBox;
            TextBox txtRenewableItem = item.FindControl("txtRenewableItem") as TextBox;
            if (cboRenewableItem != null && txtRenewableItem != null)
            {
                Answer.SetSetting(string.Concat("cboRenewableItem_", choice), cboRenewableItem.Checked);
                Answer.SetSetting(string.Concat("txtRenewableItem_", choice), txtRenewableItem.Text);
                if (cboRenewableItem.Checked)
                {
                    string reneweableItemName = string.Concat("RenewableItem_", choice);
                    string path = "home/energy/renewable";
                    CarbonExchange.Bll.AmeeProfileItem tmpProfileItem = EnsureProfileItem(reneweableItemName, profileItemFactory, dataCategoryFactory, path, string.Format("{0}={1}", RenewableChoiceName, choice));

                    decimal val = 0;
                    try
                    {
                        val = decimal.Parse(txtRenewableItem.Text);
                    }
                    catch (FormatException)
                    {
                    }

                    val = val / 12;

                    bool save = string.IsNullOrEmpty(tmpProfileItem.Id);
                    if (tmpProfileItem.GetValue<decimal>("kWhGeneratedPerMonth") != val)
                    {
                        tmpProfileItem.SetValue<decimal>("kWhGeneratedPerMonth", val);
                        save = true;
                    }

                    if (save)
                    {
                        profileItemFactory.Save(tmpProfileItem);
                    }

                    itemsToKeep.Add(Answer.SetItem(reneweableItemName, tmpProfileItem));
                }
            }
            i++;
        }

        foreach (ListItem item in cblInsulation.Items)
        {
            if (item.Selected)
            {
                string settingName = string.Concat("cblInsulation_", item.Value);
                string insulationName = string.Concat("Insulation_", item.Value);
                Answer.SetSetting(settingName, item.Selected);
                var tmpAmeeInsulationItem = EnsureProfileItem(insulationName, profileItemFactory, dataCategoryFactory, "/home/energy/insulation", string.Format("{0}={1}", InsulationChoiceName, item.Value));
                if (string.IsNullOrEmpty(tmpAmeeInsulationItem.Id))
                {
                    profileItemFactory.Save(tmpAmeeInsulationItem);
                }
                itemsToKeep.Add(Answer.SetItem(insulationName, tmpAmeeInsulationItem));
            }
        }
        return completed;
    }

    protected override object SaveViewState()
    {
        ViewState["RenewableChoices"] = RenewableChoices;
        ViewState["RenewableChoiceName"] = RenewableChoiceName;
        ViewState["InsulationChoiceName"] = InsulationChoiceName;
        return base.SaveViewState();
    }

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        RenewableChoices = ViewState["RenewableChoices"] as List<string>;
        RenewableChoiceName = ViewState["RenewableChoiceName"] as string;
        InsulationChoiceName = ViewState["InsulationChoiceName"] as string;
    }

    public override int GetActiveItemsCount()
    {
        int i = 1;
        if(pnlElectricBills.Visible)
            i++;

        if(phElectricBills.Visible)
            i += phElectricBills.Controls.OfType<Panel>().Count();
        else if(phElectricEstimate.Visible)
            i += phElectricEstimate.Controls.OfType<Panel>().Count();

        if (pnlHeatingElectric.Visible)
            i++;

        if (pnlHeatingBills.Visible)
            i++;

        if (phHeatingBills.Visible)
            i += phHeatingBills.Controls.OfType<Panel>().Count();
        else if (phHeatingEstimate.Visible)
            i += phHeatingEstimate.Controls.OfType<Panel>().Count();


        return i;
    }
   
    public override int RenderItems(int start, int end, HtmlTextWriter writer)
    {
        List<Panel> questions = new List<Panel>();
        questions.Add(pnlGreen);
        if(pnlElectricBills.Visible)
            questions.Add(pnlElectricBills);
        if (phElectricBills.Visible)
            questions.AddRange(phElectricBills.Controls.OfType<Panel>());
        else if (phElectricEstimate.Visible)
            questions.AddRange(phElectricEstimate.Controls.OfType<Panel>());

        if (pnlHeatingElectric.Visible)
            questions.Add(pnlHeatingElectric);

        if (pnlHeatingBills.Visible)
            questions.Add(pnlHeatingBills);
        
        if (phHeatingBills.Visible)
            questions.AddRange(phHeatingBills.Controls.OfType<Panel>());
        else if (phHeatingEstimate.Visible)
            questions.AddRange(phHeatingEstimate.Controls.OfType<Panel>());


        int i = 0;
        foreach (var panel in questions.Skip(start).Take(end - start))
        {
            panel.RenderControl(writer);
            i++;
        }
        return i;
    }
}
